import { useRef, useState } from "react";
import ChatForm from "./components/ChatForm";
import ChatMessage from "./components/ChatMessage";
import { useEffect } from "react";
const App = () => {
  const [chatHistory, setChatHistory] = useState([]);
  const [showChatbot, setShowChatbot] = useState(false);
  const chatBodyRef = useRef();

  const generateBotResponse = async (history) => {
    //更新历史记录
    const updateHistory = (text,isError = false) => {
      setChatHistory((prev) => [...prev.filter(msg => msg.text !== "thinking..."), { role: "model", text ,isError}])
    }

    //格式化记录为了api
    history = history.map(({ role, text }) => ({ role, parts: [{ text }] }))
    //准备请求体
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ contents: history })
    };
    //发送请求
    try {
      const response = await fetch(import.meta.env.VITE_API_URL, requestOptions)
      const data = await response.json()
      if (!response.ok) throw new Error(data.error.message || "wrong1")
      //获取api返回的response
      const apiResponseText = data.candidates[0].content.parts[0].text.replace(/\*\*(.*?)\*\*/g, "$1").trim();
      updateHistory(apiResponseText)
    } catch (error) {
      updateHistory(error.message,true)
    }
  }


  //处理长文本自动下滚
  useEffect(() => {
    //自动滚动当记录更新
    chatBodyRef.current.scrollTo({ top: chatBodyRef.current.scrollHeight, behavior: "smooth" })
  }, [chatHistory])
  return (

    <div>
      <div className={`container ${showChatbot ? "show-chatbot" : ""}`}>
        <button id="chatbot-toggler" onClick={() => setShowChatbot(prev =>!prev)}>
          <span className="iconfont icon-shang"></span>
          
        </button>
        <div className="chatbot-popup">
          {/* chatbot Header */}
          <div className="chat-header">
            <div className="header-info">
              <span class="iconfont icon-bot"></span>
              <h2 className="logo-text">WXY</h2>
            </div>
            <button onClick={() => setShowChatbot(prev =>!prev)}><span className="iconfont icon-xia"></span></button>
          </div>
          {/* chatbot Body */}
          <div ref={chatBodyRef} className="chat-body">
            <div className="message bot-message">
              <span className="iconfont icon-bot"></span>
              <p className="message-text">Hi!  😀 <br /> I'm WXY, your personal assistant.   <br />How can I help you?</p>
            </div>

            {chatHistory.map((chat, index) => (
              <ChatMessage key={index} chat={chat} />
            ))}


          </div>

          {/* chatbot Input Field */}
          <div className="chat-footer">
            <ChatForm chatHistory={chatHistory} setChatHistory={setChatHistory} generateBotResponse={generateBotResponse}></ChatForm>
          </div>
        </div>

      </div>
      <div className="footMsg">
        <div>国内请开启VPN 否则无法收到回复</div>
      </div>
    </div>
  );
}


export default App;